<template>
    <div class="posterPage" id="test">
        <van-nav-bar title="排行榜" @click-left="onClickLeft" left-text="返回" left-arrow></van-nav-bar>
        <div id="poster" style="position: relative;width: 100%">
            <img v-if="posterActive == 0 && posterType == 'sales'" src="../../../assets/img/xly.jpg"
                style="width: 100%;" @load="handleImageLoad" />
            <img v-if="posterActive == 0 && posterType == 'increment'" src="../../../assets/img/zsy.jpg"
                style="width: 100%;" @load="handleImageLoad" />
            <img v-if="posterActive == 1 && posterType == 'sales'" src="../../../assets/img/xlz.jpg"
                style="width: 100%;" @load="handleImageLoad" />
            <img v-if="posterActive == 1 && posterType == 'increment'" src="../../../assets/img/zsz.jpg"
                style="width: 100%;" @load="handleImageLoad" />
            <div v-if="listShow"
                style="width: 8rem;position: absolute; gap: .2667rem; top: 50%; left: 50%;transform: translate( -50%,-30%); display: flex;flex-direction: column;">
                <dvi
                    style="display: flex;flex-direction: column;gap: .2667rem;margin-bottom:.2667rem; justify-content: space-between;">
                    <div
                        style="background: #EE420E;padding:.0533rem .4rem; border-radius: .5333rem;font-size:.4267rem;color: #fff;">
                        <span>地点：</span>
                        <sapn>{{ location }}</sapn>
                    </div>
                    <div
                        style="background: #EE420E;padding:.0533rem .4rem; border-radius: .5333rem;font-size:.4267rem;color: #fff;">
                        <span>时间：</span>
                        <sapn>{{ formatDateRange(timeScope.start, timeScope.end) }}</sapn>
                    </div>
                </dvi>
                <div style="display: flex;gap: .5333rem; padding-bottom: .16rem;" class="borderB">
                    <span
                        style="width: .8rem;text-align: center;color: #cf3418;font-weight: bold;font-size: .4rem;">排名</span>
                    <span
                        style="width: 1.3333rem;text-align: center;color: #cf3418;font-weight: bold;font-size: .4rem;">当日值</span>
                    <span
                        style="width: 1.3333rem;text-align: center;color: #cf3418;font-weight: bold;font-size: .4rem;">{{
                            posterActive == 1? '当周值':'当月值'}}</span>
                    <span style="flex:1;text-align: center;color: #cf3418;font-weight: bold;font-size: .4rem;">渠道</span>
                </div>
                <div style="display: flex;height:1.0667rem;align-items: center; gap: .5333rem;padding-bottom: .16rem;"
                    v-for="(item, index) in paiList" :key="item" :class="{ 'borderB': index != 10 }">
                    <div style="width: .8rem;text-align: center;font-size: .4rem;">
                        <img v-if="index <= 2" :src="imgs[index]" style="width: .8667rem" />
                        <span
                            style="border-radius: 50%;width: .6333rem;height:.6333rem ;  display: inline-flex;justify-content: center;align-items: center;  font-size:.38rem ; background: #EF6246;color: #fff;"
                            v-else>{{ index + 1 }}</span>
                    </div>
                    <span style="width: 1.3333rem;text-align: center;font-size: .4rem;font-weight: bold" class="moit">{{ posterType ==
                        'sales' ? item.prev_day_sales : item.prev_day_income
                        }}</span>
                    <span style="width: 1.3333rem;text-align: center;font-size: .4rem;font-weight: bold" class="moit">{{ posterType ==
                        'sales' ? item.period_sales_count :item.period_income }}</span>
                    <span style="flex:1;text-align: center;font-weight: bold;font-size: .32rem" class="moit">{{
                        item.depart_name }}</span>
                </div>
            </div>

        </div>
        <div v-if="listShow" id="submit" style="font-size:.4267rem;border-radius: 1.3333rem;overflow: hidden;">
            <van-button @click="convertToImage" round type="danger"
                style="width: 3.2rem;background-image: linear-gradient(135deg, #FEC163 15%, #DE4313 100%);border: none;">生成海报</van-button>
        </div>
    </div>
    <van-dialog v-model:show="show" :show-cancel-button="false" :show-confirm-button="false" :overlay="false">
        <img src="../../../assets/img/none.png">
        <p>暂无数据</p>
    </van-dialog>
</template>

<script setup>
import { ImagePreview } from 'vant';
import icon1 from "../../../assets/img/icon1.png"
import icon2 from "../../../assets/img/icon2.png"
import icon3 from "../../../assets/img/icon3.png"
import { useRouter, useRoute } from "vue-router";
import html2canvas from 'html2canvas';
import { ref, nextTick, onMounted } from "vue"
import PosterInfoApi from "../api/poster"
import { parseTime } from "../../../utils/index"
import { message } from "ant-design-vue";

const router = useRouter();
const route = useRoute();
const imgs = [icon1, icon2, icon3]
const listShow = ref(false)
const location = route.query.scope
const posterType = route.query.type
const posterActive = route.query.active
const paiList = ref([])
const show = ref(false)
const timeScope = {
    start: route.query.start,
    end: route.query.end
}
onMounted(async () => {

    let { type, scope, start, end } = route.query

    let paramsData = {
        districtName: scope == '延安市' ? undefined : scope,
        startDate: parseTime(start, '{y}-{m}-{d}'),
        endDate: parseTime(end, '{y}-{m}-{d}'),
    }

    if (type == "increment") {
        let respData = await PosterInfoApi.getIncome({ ...paramsData })
        if (respData.data.code != 200) return
        paiList.value = respData.data.data
        if (paiList.value.length == 0) {
            message.error("暂无数据")
            //    show.value=true
            //    setTimeout(()=>{
            //     show.value=false
            //    },2000)
        }

    } else {
        let respData1 = await PosterInfoApi.getSales({ ...paramsData })
        if (respData1.data.code != 200) return
        paiList.value = respData1.data.data
        if (paiList.value.length == 0) {
            message.error("暂无数据")
            //     show.value=true
            //     setTimeout(()=>{
            //     show.value=false
            //    },2000)
        }
    }

    if (paiList.value.length >= 9) {
        paiList.value = paiList.value.slice(0, 10)
    } else {
        let initData = Array(10).fill({
            prev_day_income: undefined,
            period_income: undefined,
            depart_name: undefined
        }).map((item, index) => {
            if (paiList.value[index]) {
                return paiList.value[index]
            } else {
                return item
            }
        })

        paiList.value = initData
    }


})
function handleImageLoad() {
    listShow.value = true
}
const onClickLeft = () => {

    router.push({
        path: "/uniquePath-time",
        query: {
            type: route.query.type,
            scope: route.query.scope,
            active: route.query.active
        }
    });
};
function convertToImage() {
    html2canvas(document.getElementById("poster")).then(canvas => {
        // 将 canvas 转换为图片 URL
        const imgData = canvas.toDataURL("image/png");
        // // 创建一个临时的链接元素来下载图片
        // const link = document.createElement('a');
        // link.download = 'screenshot.png'; // 设置下载的文件名
        // link.href = imgData;
        // link.click(); // 模拟点击下载
        ImagePreview([
            imgData
        ]);

    }).catch(() => {
        console.log()
    });
}
function formatDateRange(startTimestamp, endTimestamp) {
    // 创建日期对象
    const startDate = new Date(Number(startTimestamp));
    const endDate = new Date(Number(endTimestamp));
    // 获取年份、月份和日期
    const startYear = startDate.getFullYear();
    const startMonth = startDate.getMonth() + 1; // 月份从0开始，所以加1
    const startDay = startDate.getDate();

    const endYear = endDate.getFullYear();
    const endMonth = endDate.getMonth() + 1;
    const endDay = endDate.getDate();

    // 格式化开始日期
    const formattedStart = `${startYear}年${startMonth}.${startDay}`;

    // 如果年份相同，结束日期不显示年份，否则显示年份
    const formattedEnd = startYear === endYear
        ? `${endMonth}.${endDay}`
        : `${endYear}年${endMonth}.${endDay}`;

    // 返回格式化后的日期范围
    return `${formattedStart}-${formattedEnd}`;
}
</script>

<style>
.posterPage {
    width: 100vw;
    background: #C31B08;
    padding-bottom: .5333rem;
}

.moit {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    /* 限制显示的行数为2 */
    -webkit-box-orient: vertical;
    overflow: hidden;
    /* 隐藏溢出的文本 */
    text-overflow: ellipsis;
    /* 显示省略号 */
    word-break:break-all
}

.borderB {
    border-bottom: 1px solid #F3DFAF;

}
</style>